#pragma once 

#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include <semaphore.h>

template <class T>
class RingQueue
{
  private:
    int _cap;
    std::vector<T> ring;
    int p_index, c_index; //生产者和消费者的下标
    sem_t sem_space, sem_data;  //信号量定义
  public:
    RingQueue(int cap): _cap(cap), ring(cap), p_index(0), c_index(0)
    {
      sem_init(&sem_data, 0, 0);
      sem_init(&sem_space, 0, 10);  //第二个参数代表为线程使用
    }
    void Put(const T& in)
    {
      sem_wait(&sem_space);
      ring[p_index] = in;
      sem_post(&sem_data);
      p_index++;
      p_index %= _cap;
    }
    void Get(T* out)
    {
      sem_wait(&sem_data);
      *out = ring[c_index];
      sem_post(&sem_space);
      c_index++;
      c_index %= _cap;
    }
    ~RingQueue()
    {
      sem_destroy(&sem_data);
      sem_destroy(&sem_space);
    }
};
